# services/user_service.py
from typing import List, Tuple
from sqlalchemy.orm import Session
from models.user import User

from common import logger


class UserService:
    @staticmethod
    def get_users(db: Session, page: int, page_size: int) -> Tuple[List[User], int]:
        try:
            skip = (page - 1) * page_size
            users_query = db.query(User).offset(skip).limit(page_size)
            total_users = db.query(User).count()
            users = users_query.all()
            return users, total_users  # 返回用户列表和总数
        except Exception as e:
            # 处理异常，例如记录日志或返回空结果
            logger.error(f"Error fetching users: {e}")
            return [], 0
    @staticmethod
    def get_user_by_id(db: Session, user_id: int) -> User:
        return db.query(User).filter(User.id == user_id).first()
    @staticmethod
    def create_user(db: Session, user: User):
        db.add(user)
        db.commit()
        db.refresh(user)  # 刷新对象，使其包含新的 ID 和其他数据库生成的值

    @staticmethod
    def update_user(db: Session, user_id: int, user_data: User):
        user = db.query(User).filter(User.id == user_id).first()
        if not user:
            return None
        user.username = user_data.username
        user.email = user_data.email
        db.commit()
        return user

    @staticmethod
    def delete_user(db: Session, user_id: int):
        user = db.query(User).filter(User.id == user_id).first()
        if not user:
            return None
        db.delete(user)
        db.commit()
